import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:lpinyin/lpinyin.dart';

import 'address_manager.dart';
import 'address_model.dart';

class AddressPickController extends GetxController {
  final TextEditingController editingController = TextEditingController();

  /// 省
  List<AddressProvince> provinceAry = [];

  /// 市
  List cityAry = [];

  /// 区/县
  List districtAry = [];

  /// 全部数据
  List<dynamic> allData = [];

  ///搜索数据
  List searchData = [];

  /// 数据源
  List<dynamic> dataSource = [];

  /// 坐标索引数组
  List indexList = [];

  /// 是否是搜索 false
  bool isSearch = false;

  bool isProvince = false;
  bool isCity = false;
  bool isDistrict = false;

  Map provinceMap = {};
  Map cityStrMap = {};

  /// 选择的地址
  List selectAddressAry = [];

  List firstData = ['中国', '海外'];

  /// 地址选择block
  late Function(List selectAddressAry)? onSelectAddress;

  ///中国/外国分类选择 true
  bool isInternational = true;

  /// 外国全部数据
  List internationalData = [];

  /// 内地选择 true 国际选择 false
  bool inlandSelect = true;

  ///不区分中国/外国分类选择 true
  bool noIsInternational = false;

  @override
  void onInit() {
    super.onInit();
    noIsInternational = Get.arguments['noIsInternational']?? false;
    inlandSelect = Get.arguments['inlandSelect']?? true;
    if (inlandSelect) {
      loadAddressDataApi();
    }

    if (noIsInternational) {
      isInternational = false;
    }

  }

  /// 获取国内地址
  loadAddressDataApi() {
    AddressManager.loadAddressData().then((value) => {
          provinceAry = value,
          for (AddressProvince provice in provinceAry)
            {
              allData.add(provice),
              for (AddressCity city in provice.cities)
                {
                  allData.add(city),
                  for (AddressDistrict district in city.district)
                    {allData.add(district)}
                }
            },
          handleGroup(provinceAry),
        });
  }

  /// 获取国外地址
  loadInternationalData() {
    AddressManager.loadInternationalData()
        .then((value) => {internationalData = value, handleGroup(value)});
  }

  /// 处理数据
  void handleGroup(List<dynamic> data) {
    Map sortMap = <String, List>{};
    //0  - 9
    for (var i = 0; i < 10; i++) {
      String key = i.toString();
      sortMap[key] = [];
    }
    //A - Z
    for (var i = 97; i < 123; i++) {
      String key = String.fromCharCode(i).toUpperCase();
      sortMap[key] = [];
    }
    //# 未分类
    sortMap['#'] = [];

    for (dynamic model in data) {
      String key = PinyinHelper.getShortPinyin(model?.name);
      if (key.isEmpty) continue;
      key = key.substring(0, 1).toUpperCase();
      if (sortMap.containsKey(key)) {
        if (sortMap[key] is List) {
          (sortMap[key] as List).add(model);
        }
      } else {
        if (sortMap[key] == null) {
          sortMap[key] = [];
        }
        (sortMap[key] as List).add(model);
      }
    }
    Map tmpMap = Map.from(sortMap);
    tmpMap.forEach((key, value) {
      if ((value as List).isEmpty) {
        sortMap.remove(key);
      }
    });
    dataSource = sortMap.values.toList();
    indexList = sortMap.keys.toList();
    update();
  }

  /// 点击cell 状态 未搜索
  clickCellMethod(dynamic) {
    if (!isProvince) {
      handleGroup(dynamic.cities);
      isProvince = true;
      provinceMap = {
        'title': dynamic.province,
        'id': dynamic.provinceid,
        'list': dynamic.cities
      };
      selectAddressAry.add(provinceMap['title']);
    } else if (!isCity) {
      handleGroup(dynamic.district);
      isCity = true;
      cityStrMap = {
        'title': dynamic.city,
        'id': dynamic.cityid,
        'list': dynamic.district
      };
      selectAddressAry.add(cityStrMap['title']);
    } else {
      selectAddressAry.add(dynamic.area);
      Get.back(result: selectAddressAry);
      selectAddressAry;
    }
  }

  /// 点击cell 状态 搜索
  clickCellSearchMethod(dynamic) {
    isSearch = !isSearch;
    for (AddressProvince provinceModel in provinceAry) {
      if (provinceModel.name == dynamic.name) {
        clickCellMethod(provinceModel);
        return;
      } else {
        for (AddressCity cityModel in provinceModel.cities) {
          if (cityModel.name == dynamic.name) {
            if (!isProvince) {
              provinceMap = {
                'title': provinceModel.province,
                'id': provinceModel.provinceid
              };
              selectAddressAry.add(provinceMap['title']);
            }
            isProvince = true;
            clickCellMethod(cityModel);
            return;
          } else {
            for (AddressDistrict districtModel in cityModel.district) {
              if (districtModel.name == dynamic.name) {
                selectAddressAry.add(provinceModel.name);
                selectAddressAry.add(cityModel.name);
                selectAddressAry.add(districtModel.name);
                Get.back(result: selectAddressAry);
                return;
              }
            }
          }
        }
      }
    }
  }

  /// 返回按钮
  goBack() {
    if (isCity) {
      provinceMap;
      AddressManager.getProvince(provinceMap['id'] ?? '').then((value) => {
            handleGroup(value!.cities),
            isCity = !isCity,
            if (selectAddressAry.length > 1)
              {selectAddressAry.removeRange(1, 2)}
          });
    } else if (isProvince) {
      handleGroup(provinceAry);
      isProvince = !isProvince;
      selectAddressAry = [];
    }
  }

  /// 搜索数据国内
  getSearchForData(String text) {
    searchData = [];
    var upSearch = editingController.text.toUpperCase();

    /// 搜索全部数据
    if (!isProvince) {
      for (dynamic model in allData) {
        if (model.name!.toUpperCase().contains(upSearch)) {
          searchData.add(model);
        }
      }
      update();
    } else if (isProvince && !isCity) {
      for (dynamic model in provinceMap['list']) {
        if (model.name!.toUpperCase().contains(upSearch)) {
          searchData.add(model);
        }
      }
    } else {
      for (dynamic model in cityStrMap['list']) {
        if (model.name!.toUpperCase().contains(upSearch)) {
          searchData.add(model);
        }
      }
    }
    update();
  }

  /// 国外搜索数据
  getSearchForDataInternational(String text) {
    searchData = [];
    var upSearch = editingController.text.toUpperCase();
    for (dynamic model in internationalData) {
      if (model.name!.toUpperCase().contains(upSearch)) {
        searchData.add(model);
      }
    }
    update();
  }

  void handleClear() {
    isSearch = false;
    searchData = [];
    update();
  }
}
